<template>
  <div class="customer-management">
    <div class="page-header">
      <h1>客户管理</h1>
      <el-input
        v-model="searchKeyword"
        placeholder="搜索客户姓名、用户名或手机号"
        style="width: 300px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>

    <el-card v-loading="loading">
      <el-table :data="filteredCustomers" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="realName" label="真实姓名" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="{ row }">
            <el-tag :type="getRoleColor(row.role)">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="手机号码" width="150">
          <template #default="{ row }">
            {{ row.phone || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱地址" width="200">
          <template #default="{ row }">
            {{ row.email || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-if="canDelete(row)"
              size="small" 
              type="danger"
              :icon="Delete"
              @click="deleteCustomer(row)"
            >
              删除
            </el-button>
            <span v-else style="color: #999; font-size: 12px;">
              当前用户
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Delete } from '@element-plus/icons-vue'
import { request } from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

interface Customer {
  id: number
  username: string
  realName: string
  phone?: string
  email?: string
  status: string
  role: string
  createdAt: string
}

const customers = ref<Customer[]>([])
const searchKeyword = ref('')
const loading = ref(false)
const authStore = useAuthStore()

const filteredCustomers = computed(() => {
  if (!searchKeyword.value.trim()) {
    return customers.value
  } else {
    return customers.value.filter(customer => 
      customer.realName.includes(searchKeyword.value) ||
      customer.username.includes(searchKeyword.value) ||
      (customer.phone && customer.phone.includes(searchKeyword.value))
    )
  }
})

const fetchCustomers = async () => {
  loading.value = true
  try {
    const data = await request.get('/users')
    customers.value = data
  } catch (error: any) {
    ElMessage.error(error.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const deleteCustomer = async (customer: Customer) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户 "${customer.realName}" (${customer.username}) 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await request.delete(`/users/${customer.id}`)
    ElMessage.success('删除用户成功')
    await fetchCustomers() // 重新获取用户列表
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除用户失败')
    }
  }
}

const canDelete = (customer: Customer) => {
  // 不能删除自己的账号
  return customer.id !== authStore.user?.id
}

const getStatusColor = (status: string) => {
  return status === 'ACTIVE' ? 'success' : 'danger'
}

const getStatusText = (status: string) => {
  return status === 'ACTIVE' ? '活跃' : '禁用'
}

const getRoleText = (role: string) => {
  return role === 'ADMIN' ? '管理员' : '普通用户'
}

const getRoleColor = (role: string) => {
  return role === 'ADMIN' ? 'warning' : 'primary'
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchCustomers()
})
</script>

<style scoped>
.customer-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0;
  color: #303133;
}
</style>